package com.jbp.service.impl;

import com.jbp.dao.PrizePatchDao;
import com.jbp.model.Gift;
import com.jbp.model.PrizePatch;
import com.jbp.service.GiftService;
import com.jbp.service.PrizePatchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.beans.Transient;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jbp.utils.PageUtils;
import com.jbp.utils.Query;
import org.springframework.transaction.annotation.Transactional;


@Service
public class PrizePatchServiceImpl extends ServiceImpl<PrizePatchDao, PrizePatch> implements PrizePatchService {
    @Autowired
    private GiftService giftService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PrizePatch> page = this.page(
                new Query<PrizePatch>().getPage(params),
                new QueryWrapper<PrizePatch>()
        );

        return new PageUtils(page);
    }

    @Override
    public boolean hasNormalGift(Integer userId) {
        List<PrizePatch> patchList = list(new QueryWrapper<PrizePatch>()
                .eq("user_id", userId)
                .eq("status", "normal")
        );
        return !patchList.isEmpty();
    }

    @Override
    @Transactional
    public List<Gift> luck(Integer userId, int price, int num){
        //查看当前用户有没有补发的礼品
        List<PrizePatch> patchList = list(new QueryWrapper<PrizePatch>()
                .eq("user_id", userId)
                .eq("price", price)
                .eq("status", "normal")
                .last("limit "+num)
        );

        List<Gift> giftList=new ArrayList<>();

        if (patchList != null && patchList.size() > 0){
            for (int i = 0; i < patchList.size(); i++) {
                PrizePatch prizePatch = patchList.get(i);
                if (prizePatch.getStep()<=num) {
                    Gift gift = giftService.getById(prizePatch.getGiftId());
                    prizePatch.setStatus("del");
                    prizePatch.setUpdateTime(new Date());
                    prizePatch.setStep(0);
                    giftList.add(gift);
                    //补发完成后 状态修改为已发 del
                    updateById(prizePatch);
                    num--;
                } else {
                    prizePatch.setStep(prizePatch.getStep()-num);
                    updateById(prizePatch);
                }
            }
        }
        return giftList;
    }
}
